using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using LibGit2Sharp;
using GitProjectManager.Models;

namespace GitProjectManager.Services
{
    public class ProjectService
    {
        private readonly ConfigService _configService;
        private AppConfig _config;

        public ProjectService(ConfigService configService)
        {
            _configService = configService;
            _config = _configService.LoadConfig();
        }

        public List<GitProject> GetAllProjects()
        {
            return _config.Projects.OrderByDescending(p => p.LastOpened).ToList();
        }

        public void AddProject(GitProject project)
        {
            if (!_config.Projects.Any(p => p.Path.Equals(project.Path, StringComparison.OrdinalIgnoreCase)))
            {
                _config.Projects.Add(project);
                SaveChanges();
            }
        }

        public void RemoveProject(string projectId)
        {
            var project = _config.Projects.FirstOrDefault(p => p.Id == projectId);
            if (project != null)
            {
                _config.Projects.Remove(project);
                SaveChanges();
            }
        }

        public void UpdateProject(GitProject project)
        {
            var existing = _config.Projects.FirstOrDefault(p => p.Id == project.Id);
            if (existing != null)
            {
                existing.Name = project.Name;
                existing.DefaultIDE = project.DefaultIDE;
                existing.Description = project.Description;
                existing.Tags = project.Tags;
                SaveChanges();
            }
        }

        // 获取所有自定义exe程序名称列表
        public List<string> GetExePrograms()
        {
            return new List<string>(_config.IDESettings.ExePrograms.Keys);
        }
        
        // 添加自定义exe程序
        public void AddExeProgram(string programName, string programPath)
        {
            if (!string.IsNullOrEmpty(programName) && !string.IsNullOrEmpty(programPath))
            {
                // 使用索引器会覆盖已存在的程序，这是正确的行为
                _config.IDESettings.ExePrograms[programName] = programPath;
                SaveChanges();
            }
        }
        
        // 移除自定义exe程序
        public void RemoveExeProgram(string programName)
        {
            if (!string.IsNullOrEmpty(programName) && _config.IDESettings.ExePrograms.ContainsKey(programName))
            {
                _config.IDESettings.ExePrograms.Remove(programName);
                SaveChanges();
            }
        }
        
        // 更新自定义exe程序
        public void UpdateExeProgram(string originalProgramName, string newProgramName, string newPath)
        {            
            if (!string.IsNullOrEmpty(originalProgramName) && !string.IsNullOrEmpty(newProgramName) && !string.IsNullOrEmpty(newPath) && _config.IDESettings.ExePrograms.ContainsKey(originalProgramName))
            {
                // 检查新名称是否已存在且与当前修改的程序不同
                if (originalProgramName != newProgramName && _config.IDESettings.ExePrograms.ContainsKey(newProgramName))
                {
                    throw new ArgumentException($"程序名称 '{newProgramName}' 已存在，请选择其他名称。");
                }
                
                // 如果程序名改变，需要先移除旧的再添加新的
                if (originalProgramName != newProgramName)
                {
                    // 更新所有引用了旧程序名的项目，使它们引用新的程序名
                    foreach (var project in _config.Projects)
                    {
                        if (project.ProgramName == originalProgramName)
                        {
                            project.ProgramName = newProgramName;
                        }
                    }
                    
                    // 移除旧的并添加新的
                    _config.IDESettings.ExePrograms.Remove(originalProgramName);
                    _config.IDESettings.ExePrograms[newProgramName] = newPath;
                }
                else
                {
                    // 只更新路径
                    _config.IDESettings.ExePrograms[originalProgramName] = newPath;
                }
                
                SaveChanges();
            }
            else
            {
                throw new ArgumentException("原始程序名称不存在或参数无效。");
            }
        }
        
        // 获取exe程序路径
        public string GetExeProgramPath(string programName)
        {
            if (!string.IsNullOrEmpty(programName) && _config.IDESettings.ExePrograms.ContainsKey(programName))
            {
                return _config.IDESettings.ExePrograms[programName];
            }
            return null;
        }
        
        public void OpenProject(GitProject project)
        {
            try
            {
                // 更新打开次数和时间
                project.OpenCount++;
                project.LastOpened = DateTime.Now;
                UpdateProject(project);

                // 打开项目
                string programToUse;
                
                // 优先使用项目指定的自定义程序
                if (!string.IsNullOrEmpty(project.ProgramName) && _config.IDESettings.ExePrograms.ContainsKey(project.ProgramName))
                {
                    programToUse = _config.IDESettings.ExePrograms[project.ProgramName];
                }
                else
                {
                    // 回退到默认IDE
                    programToUse = _config.IDESettings.IDEPaths.GetValueOrDefault(
                        project.DefaultIDE, "code");
                }

                Process.Start(new ProcessStartInfo
                {
                    FileName = programToUse,
                    Arguments = $"\"{project.Path}\"",
                    WindowStyle = ProcessWindowStyle.Hidden,
                    UseShellExecute = true,
                    // CreateNoWindow = true,
                    // 
                });
            }
            catch (Exception ex)
            {
                throw new Exception($"打开项目失败: {ex.Message}", ex);
            }
        }

        public List<GitProject> SearchProjects(string keyword)
        {
            if (string.IsNullOrWhiteSpace(keyword))
                return GetAllProjects();

            return _config.Projects.Where(p =>
                p.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
                p.Path.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
                (p.Description?.Contains(keyword, StringComparison.OrdinalIgnoreCase) ?? false) ||
                (p.Tags?.Any(t => t.Contains(keyword, StringComparison.OrdinalIgnoreCase)) ?? false)
            ).ToList();
        }

        private void SaveChanges()
        {
            _configService.SaveConfig(_config);
        }
        
        
         /// <summary>
        /// 自动扫描Git项目
        /// </summary>
        public List<Models.GitProject> AutoScanProjects(IProgress<string>? progress)
        {
            var foundProjects = new List<Models.GitProject>();
            if (progress == null) 
                return foundProjects;
            
            foreach (var scanPath in _config.ScanSettings.ScanPaths)
            {
                try
                {
                    var resolvedPath = ResolvePath(scanPath);
                    if (Directory.Exists(resolvedPath))
                    {
                        progress?.Report($"正在扫描: {resolvedPath}");
                        ScanDirectoryRecursive(resolvedPath, foundProjects, progress, 0);
                    }
                }
                catch (Exception ex)
                {
                    progress?.Report($"扫描路径 {scanPath} 时出错: {ex.Message}");
                }
            }

            // 添加到配置中（去重）
            foreach (var project in foundProjects)
            {
                if (!_config.Projects.Any(p => 
                    p.Path.Equals(project.Path, StringComparison.OrdinalIgnoreCase)))
                {
                    _config.Projects.Add(project);
                }
            }

            SaveChanges();
            return foundProjects;
        }

        /// <summary>
        /// 递归扫描目录
        /// </summary>
        private void ScanDirectoryRecursive(string directory, List<Models.GitProject> foundProjects, 
            IProgress<string>? progress, int depth)
        {
            if (depth > _config.ScanSettings.MaxDepth)
                return;

            try
            {
                // 检查当前目录是否是Git仓库
                if (IsGitRepository(directory))
                {
                    var project = CreateProjectFromPath(directory);
                    if (project != null)
                    {
                        foundProjects.Add(project);
                        progress?.Report($"找到Git项目: {project.Name}");
                    }
                    return; // Git仓库不继续深入扫描
                }

                // 扫描子目录（排除一些常见的不需要扫描的目录）
                var subDirectories = Directory.GetDirectories(directory)
                    .Where(dir => !ShouldSkipDirectory(dir))
                    .ToArray();

                foreach (var subDir in subDirectories)
                {
                    ScanDirectoryRecursive(subDir, foundProjects, progress, depth + 1);
                }
            }
            catch (UnauthorizedAccessException)
            {
                progress?.Report($"无权限访问目录: {directory}");
            }
            catch (Exception ex)
            {
                progress?.Report($"扫描目录 {directory} 时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 检查目录是否是Git仓库
        /// </summary>
        public bool IsGitRepository(string path)
        {
            var gitDir = Path.Combine(path, ".git");
            if (Directory.Exists(gitDir))
                return true;

            // 检查是否是工作树或子模块
            var gitFile = Path.Combine(path, ".git");
            if (File.Exists(gitFile))
            {
                var content = File.ReadAllText(gitFile);
                return content.Contains("gitdir:");
            }

            return false;
        }

        /// <summary>
        /// 从路径创建项目对象
        /// </summary>
        private Models.GitProject CreateProjectFromPath(string path)
        {
            try
            {
                var project = new Models.GitProject
                {
                    Name = Path.GetFileName(path),
                    Path = path,
                    DefaultIDE = _config.IDESettings.DefaultIDE,
                    AddedDate = DateTime.Now
                };

                // 获取Git信息
                UpdateGitInfo(project);

                return project;
            }
            catch (Exception)
            {
                return null!;
            }
        }

        /// <summary>
        /// 更新项目的Git信息
        /// </summary>
        public void UpdateGitInfo(Models.GitProject project)
        {
            try
            {
                if (Repository.IsValid(project.Path))
                {
                    using (var repo = new Repository(project.Path))
                    {
                        project.CurrentBranch = repo.Head.FriendlyName;
                        project.LastCommitDate = repo.Head.Tip?.Author.When.LocalDateTime;
                        
                        // 检查是否有未提交的更改
                        var status = repo.RetrieveStatus(new StatusOptions());
                        project.HasUncommittedChanges = status.Any();
                        
                        project.GitStatus = project.HasUncommittedChanges ? "有更改" : "已提交";
                    }
                }
                else
                {
                    project.GitStatus = "无效仓库";
                    project.HasUncommittedChanges = false;
                }
            }
            catch (Exception ex)
            {
                project.GitStatus = $"错误: {ex.Message}";
                project.HasUncommittedChanges = false;
            }
        }

        /// <summary>
        /// 更新所有项目的Git状态
        /// </summary>
        public void RefreshAllGitStatus(IProgress<string>? progress = null)
        {
            if(progress == null)
                return;
            
            foreach (var project in _config.Projects)
            {
                try
                {
                    progress?.Report($"更新Git状态: {project.Name}");
                    UpdateGitInfo(project);
                }
                catch (Exception ex)
                {
                    progress?.Report($"更新项目 {project.Name} 状态失败: {ex.Message}");
                }
            }
            SaveChanges();
        }

        /// <summary>
        /// 检查是否应该跳过该目录
        /// </summary>
        private bool ShouldSkipDirectory(string path)
        {
            var dirName = Path.GetFileName(path).ToLower();
            var skipDirs = new[] { "node_modules", ".git", "bin", "obj", "packages", "debug", "release", "target", "build", "dist" };
            
            if (skipDirs.Contains(dirName))
                return true;

            // 跳过隐藏目录（以点开头）
            if (dirName.StartsWith(".") && dirName != ".." && dirName != ".")
                return true;

            return false;
        }

        /// <summary>
        /// 解析路径（处理环境变量）
        /// </summary>
        private string ResolvePath(string path)
        {
            if (path.Contains("%"))
            {
                foreach (System.Collections.DictionaryEntry env in Environment.GetEnvironmentVariables())
                {
                    var envVar = $"%{env.Key}%";
                    if (path.Contains(envVar))
                    {
                        if (env.Value != null) 
                            path = path.Replace(envVar, env.Value.ToString());
                    }
                }
            }
            return Path.GetFullPath(path);
        }

    }
}